package com.usian.admin.filter;

import com.usian.admin.common.AppHttpCodeEnum;
import com.usian.admin.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        if(request.getURI().getPath().contains("/login/in")){
            return chain.filter(exchange);
        }


        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        Claims claims = AppJwtUtil.getClaimsBody(token);
        System.out.println("网关==="+claims);
        int num = AppJwtUtil.verifyToken(claims);
        if(num==-1 ||num==0){
            Integer id = (Integer)claims.get("id");
            //id  userid  在网关层鉴权通过后再放回请求头路由到下游服务去
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", id + "");
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
